<template>
  <div class="coupon-list">
    <!-- 搜索栏 -->
    <el-card class="mb-4">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="分类">
          <el-select filterable  v-model="searchForm.categoryId" clearable placeholder="请选择分类">
            <el-option :label="item.name" :value="item.id" v-for="item,index in classList" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input style="max-width: 300px;" v-model="searchForm.name" placeholder="请输入商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select filterable  v-model="searchForm.shelf" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="积分筛选">
          <el-select filterable  v-model="searchForm.sort" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="积分筛选最小值" :value="1" />
            <el-option label="积分筛选最大值" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd" v-has="'merchant:creditProduct:save'"
            style="margin-left: 30px">新增积分商品</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  
    <!-- 列表 -->
    <el-table :data="tableData" style="width: 100%;margin-top: 15px" border>
      <el-table-column prop="id" label="ID" width="40" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="categoryName" label="商品分类" />
      <el-table-column prop="imageUrl" label="商品图片" width="120">
        <template #default="{ row }">
          <el-image v-if="row.pics" style="width: 80px; height: 80px" :src="row.coverImage" :preview-src-list="[row.coverImage]"
            fit="cover" />
        </template>
      </el-table-column>
      <!-- <el-table-column prop="shopId" label="商户ID" width="80" /> -->
      <el-table-column prop="credit" label="积分" />
      <el-table-column prop="shopName" label="品牌店铺" />
      <!-- <el-table-column prop="storeAddress" label="品牌店铺店地址" /> -->
      <!-- <el-table-column prop="storeName" label="描述" /> -->
      <el-table-column prop="stock" label="库存" width="190">
        <template slot-scope="scope">
          <el-input-number style="width: 160px;" v-model="scope.row.stock" :min="0"
            @change="(value) => handleStockChange(value, scope.row)" v-has="'merchant:creditProduct:stock'" />
        </template>
      </el-table-column>
      <el-table-column prop="shelf" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.shelf" :active-value="1" :inactive-value="0"
            @change="(value) => handleStatusChange(value, scope.row)" v-has="'merchant:creditProduct:shelf'" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)" v-has="'merchant:creditProduct:update'">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)" v-has="'merchant:creditProduct:delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  
    <!-- 新增/编辑弹窗 -->
    <el-dialog :close-on-click-modal="false"  :title="dialogType === 'add' ? '新增' : '编辑'" top="10vh" :visible.sync="dialogVisible" width="80%"
       @close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="coupon-form">
        <!-- 基本信息 -->
        <div class="form-card">
          <h3 class="card-title">基本信息</h3>
          <el-row :gutter="20">
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品标题" prop="name">
                <el-input v-model="form.name" placeholder="请输入商品标题" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品分类" prop="categoryId">
                <el-select filterable  v-model="form.categoryId" placeholder="请选择分类" class="w-full">
                  <el-option :label="item.name" :value="item.id" v-for="item,index in classList" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌店铺" prop="shopId">
                <!-- <el-input v-model="form.storeName" placeholder="请输入领取门店" /> -->
                <el-select filterable  v-model="form.shopId" @change="handleShopChange" placeholder="请选择品牌店铺" class="w-full">
                  <el-option :label="item.name" :value="item.id" v-for="item,index in merchantList" :key="index" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="品牌店铺地址" prop="storeAddress">
                <el-input v-model="form.storeAddress" placeholder="请输入品牌店铺地址" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品封面图" prop="coverImage">
                <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" :show-file-list="false"
                  :on-success="handleIconSuccess1" :before-upload="beforeImageUpload">
                  <img v-if="form.coverImage" :src="form.coverImage" class="uploaded-image" />
                  <div v-else class="upload-placeholder">
                    <i class="el-icon-plus"></i>
                    <div class="upload-text">点击上传图片</div>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品轮播图" prop="pic">
                <!-- :http-request="customUpload"  -->
                <el-upload class="image-uploader" :headers="headers" :action="$uploadUrl" multiple :show-file-list="false"
                  :on-success="handleIconSuccess" :before-upload="beforeImageUpload">
                  <div class="flex_flex">
                    <div v-for="item,index in form.pics" :key="index" class="image-item">
                      <img :src="item" class="uploaded-image" />
                      <div class="delete-image" @click="handleDeleteImage(index)">删除</div>
                    </div>
                    <div class="upload-placeholder">
                      <i class="el-icon-plus"></i>
                      <div class="upload-text">点击上传图片</div>
                    </div>
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
                                                      <el-form-item label="商户" prop="merchantId">
                                                          <el-select filterable  v-model="form.merchantId" placeholder="请选择商户" class="w-full">
                                                              <el-option :label="item.nickname" :value="item.id" v-for="item,index in merchantList"
                                                                  :key="index" />
                                                          </el-select>
                                                      </el-form-item>
                                                  </el-col> -->
          </el-row>
        </div>
  
        <!-- 价格设置 -->
        <div class="form-card">
          <h3 class="card-title">价格设置</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="积分" prop="credit">
                <el-input-number v-model="form.credit" :min="0" :precision="2" :step="1" class="w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="价格" prop="price">
                <el-input-number v-model="form.price" :min="0" :precision="2" :step="1" class="w-full" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="库存" prop="stock">
                <el-input-number v-model="form.stock" :min="0" class="w-full" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
  
        <!-- 使用规则 -->
        <div class="form-card">
          <h3 class="card-title">使用规则</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <!-- <el-input type="textarea" :rows="3" v-model="form.description"
                              placeholder="请输入优惠券使用说明、限制条件等信息"></el-input> -->
                <EditorBar style="width: 100%" v-model="form.description" :catchData="catchDataAgreement"></EditorBar>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态" prop="shelf">
                <el-switch v-model="form.shelf" :active-value="1" :inactive-value="0" active-text="上架"
                  inactive-text="下架" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import EditorBar from "@/components/WangEnduit.vue";

export default {
  name: 'CouponList',
  components: {
    EditorBar
  },
  data() {
    return {
      headers: {
        'token': localStorage.getItem('token')
      },
      // 搜索表单
      searchForm: {
        categoryId: '',
        shelf: ''
      },
      action: '/file/upload',
      formLoading: false,
      classList: [],
      // 表格数据
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 弹窗相关
      dialogVisible: false,
      dialogType: 'add',
      bannerUploadUrl: '',
      iconUploadUrl: '',
      // 表单数据
      form: {
        name: '',
        categoryId: '',
        shopId: '',
        storeAddress: '',
        pics: [],
        credit: 0,
        price: 0,
        stock: 0,
        shelf: 0,
        description: '',
        merchantId: '',
        coverImage: ''
      },
      // 表单校验规则
      rules: {
        name: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
        // storeName: [{ required: true, message: '请输入领取门店', trigger: 'blur' }],
        // storeAddress: [{ required: true, message: '请输入领取门店地址', trigger: 'blur' }],
        pics: [{ required: true, message: '请上传图片', trigger: 'blur' }],
        credit: [{ required: true, message: '请输入积分', trigger: 'blur' }],
        price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
        shopId: [{ required: true, message: '请选择品牌店铺', trigger: 'blur' }],
        coverImage: [{ required: true, message: '请上传封面图片', trigger: 'blur' }]
      },
      // 标签选项
      tagOptions: ['热门', '推荐', '新品', '限时'],
      fileKey: '',
      merchantList: []
    }
  },
  async created() {
    console.log(localStorage.getItem('token'))
    await this.getCouponClass();
    this.getMerchantList();
    // this.queryDictList();

  },
  methods: {
    //基本信息富文本编辑
    catchDataAgreement(val) {
      this.form.description = val;
    },
    handleDeleteImage(index) {
      this.form.pics.splice(index, 1)
    },
    handleShopChange(value) {
      console.log(value, 'value123');
      this.form.storeAddress = this.merchantList.find(item => item.id == value)?.address
    },
    async getMerchantList() {
      const { data } = await this.$api.shopPageList({
        page: 1,
        size: 10000,
        condition: {
          categoryId: '',
          areaId: '',
          floorId: '',
        }
      })
      console.log(data, '111111');
      this.merchantList = data.result.records
    },
    async queryDictList() {
      const data = await this.$api.getDictList()
      console.log(data, 'data字典');
    },
    async customUpload(options) {
      try {
        const { file, onSuccess, onError } = options
        console.log(file.type, 'file');
        const formData = new FormData()
        formData.append('file', file)

        const response = await fetch(this.action, {
          method: 'PUT',
          body: formData,
          headers: {
            'Content-Type': ''
          },
          // headers: new Headers({
          //   "Content-Type": "image/png",
          // }),
        })
        // const response = await this.$api.uploadImage({
        //   url: this.action,
        //   file: formData,
        // // })
        console.log(response.url, 'response123123');
        console.log(response, 'response123123');

        if (!response.ok) {
          throw new Error('上传失败')
        }

        // const result = await response.json()
        console.log(response, 'result');
        onSuccess(response)
      } catch (error) {
        onError(error)
      }
    },
    async getCouponClass() {
      const { data } = await this.$api.productCategoryList({
        ...this.searchForm
      })
      this.classList = data.result
      this.getList();
    },// 关闭弹窗时清空数据
    handleDialogClose() {
      // 重置表单验证状态
      this.$refs.form.resetFields()

      // 重置表单数据到初始状态
      this.form = {
        name: '',
        categoryId: '',
        storeAddress: '',
        pics: [],
        credit: 0,
        price: 0,
        stock: 0,
        shelf: 0,
        description: '',
        shopId: '',
        coverImage: ''
      }
      this.formLoading = false
      this.dialogVisible = false
    },
    // 获取列表数据
    async getList() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          condition: {
            ...this.searchForm,
          }
        }
        if (this.searchForm.sort == 1) {
          params.condition.minCredit = 1
        } else if (this.searchForm.sort == 2) {
          params.condition.maxCredit = 1
        }
        delete params.condition.sort
        // 这里替换为实际的API调用
        const { data } = await this.$api.getCreditProductList(params)
        console.log(this.classList, 'classListclassList');
        data.result.records.forEach(item => {
          item.categoryName = this.classList.find(items => {
            return items.id == item.categoryId
          })?.name
        })
        console.log(data, 'data123123');
        this.tableData = data.result.records
        this.total = data.result.total
      } catch (error) {
        console.error('获取列表失败：', error)
        this.$message.error('获取列表失败')
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.storeName = ''
      this.searchForm.shelf = ''
      this.handleSearch()
    },

    // 新增
    handleAdd() {
      this.dialogType = 'add'
      this.dialogVisible = true
      // this.$nextTick(() => {
      //   this.$refs.form.resetFields()
      //   Object.keys(this.form).forEach(key => {
      //     this.form[key] = key === 'tags' ? [] : ''
      //   })
      // })
    },

    // 编辑
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true;
      this.iconUploadUrl = row.iconUrl
      this.bannerUploadUrl = row.banner
      this.form = {
        id: row.id,
        name: row.name,
        categoryId: row.categoryId,
        shopId: row.shopId,
        storeAddress: row.storeAddress,
        pics: row.pics || [],
        credit: row.credit,
        price: row.price,
        stock: row.stock,
        shelf: row.shelf,
        description: row.description,
        coverImage: row.coverImage,
        // shopId: row.shopId
      }
      // this.$nextTick(() => {
      //   this.$refs.form.resetFields()
      //   Object.keys(this.form).forEach(key => {
      //     if (key === 'effectDate') {
      //       this.form[key] = [row.effectStart, row.effectEnd]
      //     } else {
      //       this.form[key] = row[key]
      //     }
      //   })
      // })
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该优惠券？', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          await this.$api.deleteCreditProduct(row.id)
          this.$message.success('删除成功')
          this.getList()
        } catch (error) {
          console.error('删除失败：', error)
          this.$message.error('删除失败')
        }
      })
    },
    async beforeImageUpload(rawFile) {
      const fileName = rawFile.name
      const baseFileName = fileName.substring(0, fileName.lastIndexOf('.'))
      // const { data } = await this.$api.getUploadUrl({ filename: fileName })
      // console.log(data, 'data');
      // this.action = data.result.url
      // this.fileKey = data.result.fileKey
      // this.iconUploadUrl = data.result.uploadUrl
      const imgSize = rawFile.size / 1024 / 1024 < 10
      const imgType = ['image/jpeg', 'image/png', 'image/gif']
      if (!imgType.includes(rawFile.type))
        message.notifyWarning('上传图片不符合所需的格式！')
      if (!imgSize) message.notifyWarning(`上传图片大小不能超过 10M！`)
      return imgType.includes(rawFile.type) && imgSize
    },
    // 提交表单
    handleSubmit() {
      console.log(this.form, 'form');
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            let data = {}
            if (this.form.pics.length <= 0) {
              this.$message.error('请上传商品轮播图')
              return
            }
            if (this.dialogType === 'add') {
              data = await this.$api.addCreditProduct(this.form)
            } else {
              data = await this.$api.editCreditProduct(this.form)
            }

            this.formLoading = false
            this.$message.success(this.dialogType === 'add' ? '新增成功' : '编辑成功')
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            this.formLoading = false
            console.error('提交失败：', error)
            this.$message.error('提交失败')
          }
        }
      })
    },

    // 修改状态
    async handleStatusChange(value, row) {
      try {
        await this.$api.creditProductStatus(row.id, value)
        this.$message.success('状态修改成功')
      } catch (error) {
        console.error('状态修改失败：', error)
        this.$message.error('状态修改失败')
        row.shelf = !value // 恢复原状态
      }
    },

    // 修改库存
    async handleStockChange(value, row) {
      try {
        console.log(value, 'value123');
        await this.$api.creditProductStock(row.id, {
          stock: value
        })
        this.$message.success('库存修改成功')
      } catch (error) {
        console.error('库存修改失败：', error)
        this.$message.error('库存修改失败')
        row.stock = value // 恢复原库存
      }
    },
    // 图片上传成功回调
    async handleIconSuccess1(res) {
      this.form.coverImage = res.result.filePath
    },
    // 图片上传成功回调
    async handleIconSuccess(res) {
      console.log(res, 'res');
      // const { data } = await this.$api.downloadUrl({
      //   fileKey: res.result.filename,
      // })
      // console.log(data, 'handleIconSuccess', res);
      this.form.pics.push(res.result.filePath)
    },

    // 分页相关
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    }
  }
}
  </script>
  
  <style scoped lang="scss">
.image-item {
    position: relative;
  }
  
  .delete-image {
    position: absolute;
    bottom: 15px;
    right: 0px;
    width: 100%;
    height: 20px;
    font-size: 14px;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    cursor: pointer;
    z-index: 1000;
    line-height: 20px;
  }
  
  .flex_flex {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .coupon-form {
  
    .form-card {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 10px;
      margin-bottom: 10px;
  
      &:last-child {
        margin-bottom: 0;
      }
  
      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0 0 20px 0;
        padding-left: 10px;
        border-left: 4px solid #409EFF;
      }
    }
  
    .form-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
  
    .image-uploader {
      .uploaded-image {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 4px;
      }
  
      .upload-placeholder {
        width: 100px;
        height: 100px;
        border: 1px dashed #d9d9d9;
        border-radius: 4px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        transition: border-color 0.3s;
  
        &:hover {
          border-color: #409EFF;
        }
  
        .el-icon-plus {
          font-size: 28px;
          color: #8c939d;
        }
  
        .upload-text {
          font-size: 12px;
          color: #8c939d;
          margin-top: 8px;
        }
      }
    }
  }
  
  .w-full {
    width: 100%;
  }
  
  .coupon-list {
    padding: 20px;
  }
  
  
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    line-height: 178px;
  }
</style>